<!--
 * @Description  : 书籍详情
 * @Author       : YiDing Xue
 * @Date         : 2023-02-23
 * @LastEditors  : YiDing Xue
 * @LastEditTime : 2023-03-10
-->
<template>
  <AppPage :placeholder="false" class="bg-[#f4f4f4]" article-class="p-0" header-class="bg-[rgba(0,0,0,.05)] ">
    <template #center>
      <nut-tabs v-if="worksTypeList.length" v-model="typeTab" class="header-tab w-200 opacity-100" background="none" color="#fcd006" @change="typeChange">
        <nut-tab-pane v-for="item in worksTypeList" :key="item.moduleWorksId" :pane-key="item.moduleWorksId" :title="item.typeName" />
      </nut-tabs>
    </template>

    <section>
      <div class="h-65vh">
        <nut-image width="100vw" height="50vh" :src="worksDetail.imgUrl" />
        <div bg-white absolute left-4vw bottom-1vh w-92vw>
          <div class="h-180 p-20 c-[#717170]">
            <div flex justify-between items-center>
              <h3 font-500 c-black>{{ worksDetail.worksName }}</h3>
              <TheIcon :size="24" icon="fluent:collections-20-filled" :color="worksDetail.isCollection ? 'red' : ''" @click="collectionWorks" />
            </div>
            <p text-12 my-10>{{ worksDetail.author }}</p>
            <div class="van-hairline--bottom pt-10"></div>
            <div class="text-ellipsis--l2 text-12 mt-20">{{ worksDetail.title }}</div>
          </div>
        </div>
      </div>

      <nut-tabs v-model="detailTab" auto-height class="w-70vw m-x-auto" color="#fcd006" @change="detailTabChange">
        <nut-tab-pane title="介绍" />
        <nut-tab-pane v-if="worksDetail.type !== 3" title="目录" />
        <nut-tab-pane v-if="worksDetail.type !== 1" title="丛书" />
      </nut-tabs>

      <section v-show="detailTab === '0'" px-20>
        <nut-divider :style="{ color: '#e8e8e8', padding: '0 65px' }"><p text-black>编辑推荐</p></nut-divider>
        <p class="text-14 c-[#8e8e8e]">{{ worksDetail.intro }}</p>
        <nut-divider :style="{ color: '#e8e8e8', padding: '0 65px' }"><p text-black>购买须知</p></nut-divider>
        <div class="text-12 px-20 py-30 c-[#8e8e8e] bg-white m-25">
          <p>1. 本平台除特别标注外所有内容均为付费商品，购买后即可永久使用。平台除纸书外的所有内容均为虚拟内容服务，一经购买无法退款，请您谅解。</p>
          <p>2. 如您在购买、使用中有任何问题，可联系客服解决（在线时间 10:00:-17:00）</p>
        </div>
      </section>

      <section v-show="detailTab === '1'" px-20>
        <nut-infinite-loading v-model="infinityValue" :has-more="hasMore" @load-more="loadMore">
          <!-- 有声书目录 -->
          <div v-if="worksDetail.type === 1">
            <div flex items-center mt-30>
              <h4>免费试听</h4>
              <p class="ml-15 text-12 text-[#8e8e8e]">共 {{ freeCatalogue.length }} 篇内容</p>
            </div>

            <div class="bg-[#eee2d5] c-[#858381] mt-10 px-20 py-30 rd-10 text-14">
              <div v-for="(item, index) in freeCatalogue" :key="index" px-10>
                <div flex justify-between items-center mb-10>
                  <nut-animate type="ripple" action="click">
                    <p @click="toWorksAudio(item)">{{ item.episodeName }}</p>
                  </nut-animate>
                  <div text-center>
                    <nut-animate
                      v-if="audioStore.playStatus && audioStore.playInfo.sort === item.sort && audioStore.playInfo.albumId === worksDetail.albumId"
                      type="ripple"
                      :loop="true"
                    >
                      <TheIcon icon="material-symbols:bar-chart" :size="24" color="#fcd006" @click="play(item, false)" />
                    </nut-animate>
                    <TheIcon v-else icon="material-symbols:play-circle-rounded" :size="24" @click="play(item, true)" />
                    <p text-12>{{ item.formatSeconds }}</p>
                  </div>
                </div>
                <nut-divider v-if="index !== freeCatalogue.length - 1" :style="{ color: '#ddcec0' }" />
              </div>
            </div>

            <div flex items-center mt-30>
              <h4>收费内容</h4>
              <p class="ml-15 text-12 text-[#8e8e8e]">共 {{ 169 }} 篇内容</p>
            </div>

            <div class="bg-white c-[#7b7b7b] mt-10 px-20 py-30 rd-10 text-14">
              <div v-for="(item, index) in catalogueList" :key="index" px-10>
                <div flex justify-between items-center mb-10>
                  <nut-animate type="ripple" action="click">
                    <p @click="toWorksAudio(item)">{{ item.episodeName }}</p>
                  </nut-animate>
                  <div text-center>
                    <nut-animate
                      v-if="audioStore.playStatus && audioStore.playInfo.sort === item.sort && audioStore.playInfo.albumId === worksDetail.albumId"
                      type="ripple"
                      :loop="true"
                    >
                      <TheIcon icon="material-symbols:bar-chart" :size="24" color="#fcd006" @click="play(item, false)" />
                    </nut-animate>
                    <div v-else>
                      <TheIcon :icon="item.lock ? 'material-symbols:lock-person' : 'material-symbols:play-circle-rounded'" :size="24" @click="play(item, true)" />
                    </div>
                    <p text-12>{{ item.formatSeconds }}</p>
                  </div>
                </div>
                <nut-divider v-if="index !== catalogueList.length - 1" :style="{ color: '#ddcec0' }" />
              </div>
            </div>
            <footer h-75 />
          </div>
          <!-- 电子书目录 -->
          <n-card v-if="worksDetail.type === 2">
            <div v-for="(item, index) in catalogueList" :key="item.id">
              {{ item.name }}
              <n-divider v-if="index !== catalogueList.length - 1" />
            </div>
          </n-card>
        </nut-infinite-loading>
      </section>
    </section>

    <footer class="footer-border fixed text-12 flex justify-around w-100vw bg-white bottom-0">
      <div text-center py-5>
        <TheIcon icon="mdi:home-lightning-bolt" :size="24" color="#000" />
        <p>浙江文艺出版社</p>
      </div>
      <div text-center py-5>
        <TheIcon icon="ic:baseline-wechat" :size="24" color="#000" />
        <p>客服</p>
      </div>
      <div text-center py-5>
        <p text-16 fw-600>￥{{ 0 }}</p>
        <n-button size="tiny" color="#fcd006" text-color="#000" round strong> <p px-5>购买</p> </n-button>
      </div>
    </footer>
    <footer h-75 />
  </AppPage>
</template>

<script setup>
import { useAudioStore, useUserStore } from '@/store'
import { worksType, worksInfo, catalogue, audioSource, addCollectionWorks } from '~/src/api/works'
import { isEmpty } from '~/src/utils/common'

const audioStore = useAudioStore()
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const detailTab = ref('1')
const worksTypeList = ref([]) // 作品的种类
const typeTab = ref('') // 作品总类下标 moduleWorksId
const worksDetail = ref({}) // 作品详情
const freeCatalogue = ref([]) // 免费专辑目录
const catalogueList = ref([]) // 目录
const infinityValue = ref(false) // 是否触发滚动加载
const hasMore = ref(true) // 是否还有更多数据
const total = ref(0) // 数据总数
const hasCollection = ref(0) // 是否收藏了作品

// 分页参数
let params = { page: 1, limit: 10, moduleWorksId: '', type: 1 }

onMounted(() => {
  typeTab.value = route.query.moduleWorksId
  getWorksType()
  getWorksDetail()
})

/** 获取作品种类 */
const getWorksType = async () => {
  const result = await worksType(route.query.worksName)
  worksTypeList.value = result.data
}

/** 获取作品对应种类的详情 */
const getWorksDetail = async () => {
  const result = await worksInfo(typeTab.value)
  worksDetail.value = result.data
  if (worksDetail.value.type !== 3) {
    getCatalogue()
  }
}

/** 获取目录 */
const getCatalogue = async () => {
  params.moduleWorksId = worksDetail.value.moduleWorksId
  params.type = worksDetail.value.type
  const { data: result } = await catalogue(params)
  // 是否有数据
  if (result.list.length) {
    // 有声书目录 免费目录和去掉免费目录
    if (worksDetail.value.type === 1) {
      if (params.page === 1) {
        freeCatalogue.value = result.list.slice(0, worksDetail.value.freeCount)
      }

      let dataList = params.page === 1 ? result.list.slice(worksDetail.value.freeCount) : result.list
      catalogueList.value = [...catalogueList.value, ...dataList]
      total.value = result.total || 0
    }
    // 电子书目录
    if (worksDetail.value.type === 2) {
      catalogueList.value = [...catalogueList.value, ...result.list]
      total.value = result.total || 0
    }
    return
  }
  hasMore.value = false
}

/** 收藏作品 */
const collectionWorks = async () => {
  if (isEmpty(userStore.phoneNumber)) {
    return $message.warning('收藏前需要绑定电话号码哦')
  }

  // 电话号码存在时，才进行查询
  if (!isEmpty(userStore.phoneNumber)) {
    const result = await addCollectionWorks(userStore.phoneNumber, worksDetail.value.moduleWorksId)
    if (isEmpty(result.data)) {
      hasCollection.value = 0
    } else {
      hasCollection.value = 1
    }
  }
}

/** 切换作品种类 */
const typeChange = () => {
  // 重置分页参数
  params = { page: 1, limit: 10, moduleWorksId: '', type: 1 }
  getWorksDetail()
}

/** 切换作品详情 */
const detailTabChange = ({ paneKey }) => {
  if (paneKey === '1') {
    getCatalogue()
  }
}

/** 触底加载 */
const loadMore = () => {
  if (detailTab.value === 0) {
    infinityValue.value = false
    return
  }
  infinityValue.value = true
  if (hasMore.value) {
    params.page++
    getCatalogue()
    setTimeout(() => {
      infinityValue.value = false
    }, 800)
  }
}

/** 前往播放器页 */
const toWorksAudio = async playInfo => {
  // 判断是否需要付费
  if (playInfo.lock) {
    $message.warning('请进入【我的】页面添加一对一专属客服')
    return
  }
  // 如果当前播放的资源和要点击资源一样不需要重新查
  if (worksDetail.value.albumId === audioStore.playInfo.albumId && playInfo.sort === audioStore.playInfo.sort) {
    router.push({ name: 'worksAudio', query: { moduleWorksId: worksDetail.value.moduleWorksId } })
    return
  }

  router.push({ name: 'worksAudio', query: { moduleWorksId: worksDetail.value.moduleWorksId, albumId: worksDetail.value.albumId, sort: playInfo.sort } })
}

/** 点击音频播放 */
const play = async (playInfo, playStatus) => {
  // 判断是否需要付费
  if (playInfo.lock) {
    $message.warning('请进入【我的】页面添加一对一专属客服')
    return
  }

  if (worksDetail.value.albumId === audioStore.playInfo.albumId && playInfo.sort === audioStore.playInfo.sort) {
    audioStore.setPlayStatus(playStatus)
    return
  }

  const { data: result } = await audioSource(worksDetail.value.albumId, playInfo.sort)
  if (result) {
    audioStore.setPlayInfo(result)
    audioStore.setPlayStatus(playStatus)
  }
}
</script>

<style lang="scss">
.nut-tabs__titles {
  padding: 0;
}
.nut-tab-pane {
  padding: 0;
  background: none;
}

.header-tab {
  --nut-tabs-titles-item-color: #fff;
  --nut-tabs-titles-item-active-color: #fff;
}

.footer-border {
  border-top-left-radius: 40px;
  border-top-right-radius: 40px;
}
</style>
